package com.jxau.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.jxau.subject.common.enums.IsDeletedFlagEnum;
import com.jxau.subject.domain.convert.SubjectCategoryConvert;
import com.jxau.subject.domain.entity.SubjectCategoryBO;
import com.jxau.subject.domain.entity.SubjectLabelBO;
import com.jxau.subject.domain.service.SubjectCategoryDomainService;
import com.jxau.subject.domain.util.CacheUtil;
import com.jxau.subject.infra.basic.entity.SubjectCategory;
import com.jxau.subject.infra.basic.entity.SubjectLabel;
import com.jxau.subject.infra.basic.entity.SubjectMapping;
import com.jxau.subject.infra.basic.service.SubjectCategoryService;
import com.jxau.subject.infra.basic.service.SubjectLabelService;
import com.jxau.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private ThreadPoolExecutor labelThreadPool;
    @Resource
    private CacheUtil cacheUtil;
    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryDomainServiceImpl.add.subjectCategoryBO: {}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategoryBO);

        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        List<SubjectCategory> subjectCategoryBOS = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConvert.INSTANCE.convertCategoryToBo(subjectCategoryBOS);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryDomainServiceImpl.queryPrimaryCategory.subjectCategoryBOList: {}", JSON.toJSONString(subjectCategoryBOList));
        }
        subjectCategoryBOList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return subjectCategoryBOList;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConvert.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }
    //版本一
//    @Override
//    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
//        //先查出该大类下的所有分类
//        SubjectCategory subjectCategory = new SubjectCategory();
//        subjectCategory.setParentId(subjectCategoryBO.getParentId());
//        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
//        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
//        if(log.isInfoEnabled()){
//            log.info("SubjectCategoryDomainServiceImpl.queryCategoryAndLabel.subjectCategoryList: {}", JSON.toJSONString(subjectCategoryList));
//        }
//
//        //一次性查出所有标签
//        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConvert.INSTANCE.convertCategoryToBo(subjectCategoryList);
//        subjectCategoryBOList.forEach(categoryBo -> {
//            //查出该分类下的所有标签
//            SubjectMapping subjectMapping = new SubjectMapping();
//            subjectMapping.setCategoryId(categoryBo.getId());
//            List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
//            if(CollectionUtils.isEmpty(subjectMappingList)){
//                return;
//            }
//            List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
//            List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
//            List<SubjectLabelBO> labelBOList = new LinkedList<>();
//            labelList.forEach(label -> {
//                SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
//                subjectLabelBO.setId(label.getId());
//                subjectLabelBO.setLabelName(label.getLabelName());
//                subjectLabelBO.setCategoryId(label.getCategoryId());
//                subjectLabelBO.setSortNum(label.getSortNum());
//                labelBOList.add(subjectLabelBO);
//            });
//            categoryBo.setLabelBOList(labelBOList);
//        });
//        return subjectCategoryBOList;
//    }
//版本二
//    @SneakyThrows
//    @Override
//    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
//        //先查出该大类下的所有分类
//        SubjectCategory subjectCategory = new SubjectCategory();
//        subjectCategory.setParentId(subjectCategoryBO.getId());
//        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
//        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
//        if(log.isInfoEnabled()){
//            log.info("SubjectCategoryDomainServiceImpl.queryCategoryAndLabel.subjectCategoryList: {}", JSON.toJSONString(subjectCategoryList));
//        }
//
//        //一次性查出所有标签
//        List<FutureTask<Map<Long, List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
//        Map<Long, List<SubjectLabelBO>> sumMap = new HashMap<>();
//
//        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConvert.INSTANCE.convertCategoryToBo(subjectCategoryList);
//        subjectCategoryBOList.forEach(categoryBo -> {
//            FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask = new FutureTask<>(() -> {
//                Map<Long, List<SubjectLabelBO>> labelBOListMap = getLabelBOList(categoryBo);
//                return labelBOListMap;
//            });
//            futureTaskList.add(futureTask);
//            labelThreadPool.submit(futureTask);
//        });
//        for (FutureTask<Map<Long, List<SubjectLabelBO>>> future : futureTaskList) {
//            Map<Long, List<SubjectLabelBO>> resultMap = future.get();
//            if(CollectionUtils.isEmpty(resultMap)){
//                continue;
//            }
//            sumMap.putAll(resultMap);
//        }
//        subjectCategoryBOList.forEach(categoryBo -> {
//            categoryBo.setLabelBOList(sumMap.get(categoryBo.getId()));
//        });
//        return subjectCategoryBOList;
//    }
//
//    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO categoryBo) {
//        Map<Long, List<SubjectLabelBO>> lableMap = new HashMap<>();
//        //查出该分类下的所有标签
//        SubjectMapping subjectMapping = new SubjectMapping();
//        subjectMapping.setCategoryId(categoryBo.getId());
//        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
//        if(CollectionUtils.isEmpty(subjectMappingList)){
//            return null;
//        }
//        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
//        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
//        List<SubjectLabelBO> labelBOList = new LinkedList<>();
//        labelList.forEach(label -> {
//            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
//            subjectLabelBO.setId(label.getId());
//            subjectLabelBO.setLabelName(label.getLabelName());
//            subjectLabelBO.setCategoryId(label.getCategoryId());
//            subjectLabelBO.setSortNum(label.getSortNum());
//            labelBOList.add(subjectLabelBO);
//        });
//        lableMap.put(categoryBo.getId(), labelBOList);
//        return lableMap;
//    }
    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
        List<SubjectCategoryBO> subjectCategoryBOS = cacheUtil.getResult(cacheKey,
                SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        //先查出该大类下的所有分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainServiceImpl.queryCategoryAndLabel.subjectCategoryList: {}", JSON.toJSONString(subjectCategoryList));
        }

        //一次性查出所有标签
        Map<Long, List<SubjectLabelBO>> sumMap = new HashMap<>();

        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConvert.INSTANCE.convertCategoryToBo(subjectCategoryList);
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = subjectCategoryBOList.stream().map(categoryBo ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(categoryBo), labelThreadPool)
        ).collect(Collectors.toList());

        completableFutureList.forEach(future -> {
                    Map<Long, List<SubjectLabelBO>> resultMap = null;
                    try {
                        resultMap = future.get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                    sumMap.putAll(resultMap);
        });
        subjectCategoryBOList.forEach(categoryBo -> {
            categoryBo.setLabelBOList(sumMap.get(categoryBo.getId()));
        });
        return subjectCategoryBOList;
    }

    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO categoryBo) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryDomainServiceImpl.getLabelBOList.categoryBo: {}", JSON.toJSONString(categoryBo));
        }
            Map<Long, List<SubjectLabelBO>> lableMap = new HashMap<>();
            //查出该分类下的所有标签
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setCategoryId(categoryBo.getId());
            List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
            if (CollectionUtils.isEmpty(subjectMappingList)) {
                return null;
            }
            List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
            List<SubjectLabelBO> labelBOList = new LinkedList<>();
            labelList.forEach(label -> {
                SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
                subjectLabelBO.setId(label.getId());
                subjectLabelBO.setLabelName(label.getLabelName());
                subjectLabelBO.setCategoryId(label.getCategoryId());
                subjectLabelBO.setSortNum(label.getSortNum());
                labelBOList.add(subjectLabelBO);
            });
            lableMap.put(categoryBo.getId(), labelBOList);
            return lableMap;
        }
}
